<template>

</template>

<script setup>
import { createApp, watch, onBeforeUnmount } from "vue";
import { loadModule } from 'vue3-sfc-loader'
import * as echarts from 'echarts'
import VChart from 'vue-charts';


const props = defineProps({
    chartStr: {
        type: String,
        default: ''
    },
    containerId: {
        type: String,
        default: ''
    }
})



let currentApp = null;
let currentStyle = null;

const processComponentString = (str) => {
    str = str.replace(/import.*from.*['"]vue-echarts['"];?\n?/g, '');
    str = str.replace(/import.*from.*['"]echarts['"];?\n?/g, '');
    str = str.replace(/components:\s*{\s*VChart,?\s*},?/g, '');
    str = str.replace(/<v-chart/g, '<vue-echarts');
    str = str.replace(/<\/v-chart>/g, '</vue-echarts>');
    return str
};

onBeforeUnmount(() => {
    if (currentApp) {
        currentApp.unmount();
        currentApp = null;
    }
    if (currentStyle) {
        currentStyle.remove();
        currentStyle = null;
    }
})

watch(
    () => props.chartStr,
    async (newVal) => {
        if (newVal) {
            try {
                // 清理之前的实例
                if (currentApp) {
                    currentApp.unmount();
                    currentApp = null;
                }
                const options = {
                    moduleCache: {
                        vue: Vue
                    },
                    getFile(url) {
                        if (url === 'file.vue') {
                            const processedStr = processComponentString(props.chartStr);
                            return Promise.resolve(processedStr)
                        }
                    },
                    addStyle(textContent) {
                        const style = document.createElement('style');
                        style.textContent = textContent;
                        document.head.appendChild(style);
                        return style;
                    },
                    handleModule: async (type, source, path, options) => {
                        if (type === '.vue') {
                            return Vue.defineComponent(source.default);
                        }
                    }
                };
                // 加载组件
                const component = await loadModule('file.vue', options);
                // 创建新实例
                const app = createApp(component).use(echarts).component('vue-echarts', VChart);

                app.config.globalProperties.$echarts = echarts;
                app.config.globalProperties.echarts = echarts;

                app.mount(`#${props.containerId}`);
                currentApp = app;
            } catch (error) {
                console.error('创建图表失败:', error);
            }
        }
    },
    { immediate: true }
)
</script>

<style scoped>
#demoChart {
    width: 100%;
    height: 100%;
}
</style>